package com.weidong.mybbs.controller;

import com.weidong.mybbs.annotation.SkipAuthValid;
import com.weidong.mybbs.config.FrontMenuConfig;
import com.weidong.mybbs.config.frontmenu.FrontMenu;
import com.weidong.mybbs.exception.BusinessException;
import com.weidong.mybbs.service.AuthService;
import com.weidong.mybbs.service.CaptcheService;
import com.weidong.mybbs.service.PermissionService;
import com.weidong.mybbs.util.AjaxResult;
import com.weidong.mybbs.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@Slf4j
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;
    @Autowired
    private CaptcheService captcheService;
    @Autowired
    private FrontMenuConfig frontMenuConfig;
    @Autowired
    private PermissionService permissionService;

    @PostMapping(value = "/doLogin")
    @ResponseBody
    @SkipAuthValid
    public AjaxResult doLogin(@RequestParam String username,
                            @RequestParam String password,
                            @RequestParam String captcha,
                            @RequestParam(required = false,defaultValue = "false") boolean rememberMe,
                            HttpServletRequest request,
                            HttpServletResponse response){
        //验证验证码
        if (!captcheService.validImgCaptcha(authService.getSessionId(request),captcha)){
            throw new BusinessException("验证码有误");
        }
        Cookie cookie = authService.login(username,password, RequestUtil.getClientIp(request),rememberMe);
        response.addCookie(cookie);
        return AjaxResult.success();
    }

    @GetMapping("/login")
    @SkipAuthValid
    public String login(){
        return "login";
    }


    /**
     * 菜单栏tree
     * @return
     */
    @GetMapping("/frontMenuTree")
    @ResponseBody
    public AjaxResult frontMenuTree(HttpServletRequest request){
        List<FrontMenu> list = frontMenuConfig.getAsTree(permissionService.getUserPermissions(authService.getCurrentUser(request).getUserId()));
        return AjaxResult.success(list);
    }
}
